package com.movie.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*") // 这个过滤器会拦截所有请求
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作（可以为空）
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);

        String requestURI = request.getRequestURI();

        // 如果用户已经登录，允许继续访问
        if (session != null && session.getAttribute("user") != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 检查当前请求是否是登录页、注册页等允许访问的页面
            if (requestURI.contains("/login") || requestURI.contains("/register") || requestURI.contains("/css") || requestURI.contains("/js")) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                // 未登录，重定向到登录页面
                response.sendRedirect("login.jsp");
            }
        }
    }

    @Override
    public void destroy() {
        // 销毁操作（可以为空）
    }
}
